﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;

namespace eTerm.ASynClientSDK.Utils {
    /// <summary>
    /// C#汉字Unicode编码相互转换
    /// </summary>
   public static class GB2312UnicodeUtil {

       private static List<GB2312Unicode> characters = new List<GB2312Unicode>();

       /// <summary>
       /// 从资源文件读取字典并缓存起来
       /// </summary>
       private static void ReadResources() {
           if (characters.Count > 0) return;
           Assembly asm=typeof(GB2312UnicodeUtil).Assembly;
           using (Stream stream = asm.GetManifestResourceStream(string.Format(@"{0}.Character.txt",typeof(GB2312UnicodeUtil).Namespace))) {
               StreamReader sr = new StreamReader(stream, Encoding.Default);
               while(true) {
                   string l = sr.ReadLine();
                   if (string.IsNullOrEmpty(l)) break;
                   string[] lineAry = l.Split(new char[] {' ','\t'}, StringSplitOptions.RemoveEmptyEntries);
                   if(lineAry.Length!=4)continue;
                   GB2312Unicode unicode = new GB2312Unicode() { 
                     GB2312=lineAry[1],
                      IsSpecial=lineAry[2].Trim()==@"1",
                       PinYin=lineAry[3].Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries).ToList(),
                     Unicode =ushort.Parse(lineAry[0])
                   } ;
                   characters.Add(unicode);
               }
           }
       }

       /// <summary>
       /// 默认转换，首字母大写，不分割
       /// </summary>
       /// <param name="chineseString"></param>
       /// <returns></returns>
       public static string FullConvert(string chineseString) {
           ReadResources();
           StringBuilder sb = new StringBuilder();
           foreach (char i in chineseString.ToCharArray()) {
               ushort uni = ToUnicode(i);
               GB2312Unicode code = characters.FirstOrDefault(t => t.Unicode == uni);
               if (code == null) continue;
               CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
               TextInfo textInfo = cultureInfo.TextInfo;


               sb.Append(textInfo.ToTitleCase(code.PinYin.FirstOrDefault()));
           }
           return Regex.Replace( sb.ToString(),@"\d",string.Empty, RegexOptions.IgnoreCase| RegexOptions.Multiline);
       }


        /// <summary>
        /// 汉字转换为Unicode编码(单汉字)
        /// </summary>
        /// <param name="str">要编码的汉字字符串</param>
        /// <returns>Unicode编码的的字符串</returns>
        public static ushort ToUnicode(char str) {
           ushort uni = (ushort)str;
           return uni;
        }



        /// <summary>
        /// 将Unicode编码转换为汉字字符串
        /// </summary>
        /// <param name="str">Unicode编码字符串</param>
        /// <returns>汉字字符串</returns>
        public static string ToGB2312(string str) {
            string r = "";
            MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            byte[] bts = new byte[2];
            foreach (Match m in mc) {
                bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                r += Encoding.Unicode.GetString(bts);
            }
            return r;
        }


        class GB2312Unicode {

            public GB2312Unicode() {
                PinYin = new List<string>();
            }

            public ushort Unicode { get; set; }

            public string GB2312 { get; set; }

            public bool IsSpecial { get; set; }

            public List<string> PinYin { get; set; }
        }
    }
}
